<?php

namespace App\Http\Controllers;

use App\Models\Fans;
use App\Tools\TencentYoutuyun\Http;
use App\Tools\TencentYoutuyun\YouTu;
use App\Tools\TencentYoutuyun\TencentYoutu;
use App\Tools\TencentYoutuyun\Conf;
use App\Tools\TencentYoutuyun\Auth;
use Illuminate\Http\Request;

class ScanController extends Controller
{
  public function __construct()
  {
    Conf::setAppInfo(env('YOUTU_APP_ID'), env('YOUTU_SECRET_ID'), env('YOUTU_SECRET_KEY'), env('YOUTU_USER_ID'), conf::API_YOUTU_END_POINT);
  }

  public function scan()
  {
    return view('scan');
  }

  public function handleScan(Request $request)
  {
    $this->validate($request, [
      'form_data' => 'required|array|min:1',
      'form_data.*.name' => 'required|between:1,190',
      'form_data.*.phone' => 'required|regex:/^1[34578][0-9]{9}$/',
    ]);
    $insert = [];
    foreach ($request->form_data as $key => $form_datum) {
      $insert[$key]['name'] = $form_datum['name'];
      $insert[$key]['phone'] = $form_datum['phone'];
      $insert[$key]['sex'] = 2;
      $insert[$key]['type'] = 1;
    }
    Fans::insertOnDuplicateKey($insert); // 自动更新重复数据
    return response()->json(['code' => 0, 'message' => '操作成功']);
  }

  public function process(Request $request)
  {
    $this->validate($request, [
      'result_file' => 'required|array|min:1',
      'result_file.*' => 'required|mimes:png,jpg,jpeg'
    ]);
    if ($request->hasFile('result_file')) {
      $destinationPath = 'uploads/sheets/';
      $images = [];
      foreach ($request->result_file as $key => $file) {
        $extension = $file->getClientOriginalExtension();
        $filename = str_random(10) . '.' . $extension;
        $file->move($destinationPath, $filename);
        $images[$key]['name'] = $filename;
        $images[$key]['url'] = asset($destinationPath . $filename);
      }
      $results = $this->identify($images);
      foreach ($results as $result) {
        if(!isset($result['errorcode']) && !isset($result['items'])) {
          session()->flash('danger', '无法识别上传的图片');
          return redirect()->back();
        }
      }
      foreach ($images as $image) {
        \File::delete($destinationPath . $image['name']);
      }
      return $this->confirm($results);
    }
    session()->flash('danger', '没有上传图片');
    return redirect()->back();
  }

  public function confirm($results)
  {
    return view('confirm', compact('results'));
  }

  public function identify($images)
  {
    if (!is_array($images)) {
      $images = compact('images');
    }
    $result = [];
    foreach ($images as $key => $image) {
      $uploadRet = TencentYoutu::generalocrurl($image['url'], 1);
      $result[$key] = $uploadRet;
    }
    return $result;
  }

  public function successed()
  {
    return view('successed');
  }

  public function failed()
  {
    return view('failed');
  }
}
